package com.example.costumview.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.example.costumview.R;

public class TelescopeView extends View {

    private Paint mPaint;
    private Bitmap mBmp,mBitmapBG;

    private float mRadius = 150;

    private float mX=-1, mY=-1;

    public TelescopeView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mBmp = BitmapFactory.decodeResource(getResources(), R.drawable.qifengle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (mBitmapBG == null){
            mBitmapBG=Bitmap.createBitmap(getWidth(),getHeight(),Bitmap.Config.ARGB_8888);
            Canvas canvasBG=new Canvas(mBitmapBG);
            canvasBG.drawBitmap(mBmp,null,new Rect(0,0,getWidth(),getHeight()),mPaint);
        }

        if (mX!=-1 && mY!=-1){
            mPaint.setShader(new BitmapShader(mBitmapBG,Shader.TileMode.REPEAT,Shader.TileMode.REPEAT));
            canvas.drawCircle(mX, mY, mRadius, mPaint);
        }


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mX = event.getX();
                mY = event.getY();
                postInvalidate();
                return true;
            case MotionEvent.ACTION_MOVE:
                mX = event.getX();
                mY = event.getY();
                break;
            case MotionEvent.ACTION_UP:
                mX = -1;
                mY = -1;
                break;
        }
        postInvalidate();
        return super.onTouchEvent(event);
    }
}
